﻿using AutoMapper.Internal.Mappers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;

namespace Himp.Outpatient
{
    /// <summary>
    /// 工作站登录记录
    /// </summary>
    public class OtpWkstLoginRecService: OutpatientAppService, IOtpWkstLoginRecService
    {
        private IRepository<OtpWkstLoginRec, Guid> _wkstLoginRecRepository;
        private IOtpRgstRecService _otpRgstRecService;

        public OtpWkstLoginRecService(IRepository<OtpWkstLoginRec, Guid> wkstLoginRecRepository
            , IOtpRgstRecService otpRgstRecService)
        {
            _wkstLoginRecRepository = wkstLoginRecRepository;
            _otpRgstRecService = otpRgstRecService;
        }

        public async Task<PagedResultDto<OtpWkstLoginRecDto>> GetListAsync(OtpWkstLoginRecInput input)
        {
            var iQuery = await _wkstLoginRecRepository.GetQueryableAsync();

            //iQuery = iQuery.WhereIf(!string.IsNullOrEmpty(input.Filter), d => d.WkstLoginRecCodg.Contains(input.Filter) || d.WkstLoginRecName.Contains(input.Filter));

            if (input.Pi == 0)
            {
                var itemsDto = ObjectMapper.Map<List<OtpWkstLoginRec>, List<OtpWkstLoginRecDto>>(iQuery.ToList());

                return new PagedResultDto<OtpWkstLoginRecDto>(itemsDto.Count, itemsDto);
            }
            else
            {
                var totalCount = iQuery.Count();
                var items = iQuery.Page(input.Pi, input.Ps);
                var itemsDto = ObjectMapper.Map<List<OtpWkstLoginRec>, List<OtpWkstLoginRecDto>>(items.ToList());

                return new PagedResultDto<OtpWkstLoginRecDto>(totalCount, itemsDto);
            }
        }

        /// <summary>
        /// 签到
        /// </summary>
        /// <param name="otpRgstRec"></param>
        /// <returns></returns>
        public async Task<OtpWkstLoginRecDto> PostSignAsync(OtpWkstLoginRecCreateDto input)
        {
            var wkstLoginRec = ObjectMapper.Map<OtpWkstLoginRecCreateDto, OtpWkstLoginRec>(input);
            wkstLoginRec.LoginDrCodg = CurrentUser.Name;
            wkstLoginRec.LoginDrName = CurrentUser.UserName;
            wkstLoginRec.LoginDrId = CurrentUser.Id ?? Guid.NewGuid();

            wkstLoginRec = await _wkstLoginRecRepository.InsertAsync(wkstLoginRec);
            var wkstLoginRecDto = ObjectMapper.Map<OtpWkstLoginRec, OtpWkstLoginRecDto>(wkstLoginRec);

            return wkstLoginRecDto;
        }
    }
}
